//对象收编变量
//全局变量  键值对

//initData初始化数据 获取所需要的数据
//动画  animate管理所有动画函数
var bird={
     skyPosition:0,
     skyStep:2,
     birdTop:220,
     birdStepY:0,
     startColor:'blue',
     //点击开始后，字体放大缩小和小鸟蹦跶不执行
     startFlag:false,   //默认游戏未开始
     minTop:0,
     maxTop:570,
     pipeLength:7,
     pipeArr:[
        //  {up:dom,down:dom},
     ],
     pipeLastIndex:6,
     score:0,
     

    /**
     * 初始化函数  不需要用一次调用一次
     */
    init:function(){
        this.initData();
        this.animate();
        this.handle();
        if(sessionStorage.getItem('play')){
            this.start();
        }
    },
    initData:function(){
        this.el=document.getElementById("game");
        this.oBird=this.el.getElementsByClassName("bird")[0];
        this.oStart=this.el.getElementsByClassName("start")[0];
        this.oScore=this.el.getElementsByClassName("score")[0];
        this.oMask=this.el.getElementsByClassName("mask")[0];
        this.oEnd=this.el.getElementsByClassName("end")[0];
        this.oFinalScore=this.oEnd.getElementsByClassName('final-score')[0];
        this.oRankList=this.oEnd.getElementsByClassName('rank-list')[0];
        this.oRestart=this.oEnd.getElementsByClassName('restart')[0];

        this.scoreArr=this.getScore();
   

        // console.log(el);
    },
    getScore:function(){
        var scoreArr=getLocal('score');
        return  scoreArr ? scoreArr : [];
    },
   
    //添加一个分数
    setScore:function(){
        this.scoreArr.push({
            score:this.score,
            time:this.getDate(),
        })
        // this.scoreArr.sort(function(a,b){
        //     return b.score - a.score;
        // })
        setLocal('score',this.scoreArr);
        //console.log(this.scoreArr);

    },
  
    getDate:function(){
        var d=new Date();
        var year=d.getFullYear();
        var month=formatNum(d.getMonth()+1);
        var day=formatNum(d.getDate());
        var hour=formatNum(d.getHours());
        var minute=formatNum(d.getMinutes());
        var second=formatNum(d.getSeconds());
        return `${year}.${month}.${day} ${hour}:${minute}:${second}`;
    },
    animate:function(){
        var count=0;
        var self=this;
        this.timer=setInterval(function(){
            self.skyMove();
            if(self.startFlag){
                self.birdDrop();
                self.pipeMove();
            }
            if(++ count % 10 == 0){

                //点击开始按钮birdJump和startBound不执行
                if(!self.startFlag){
                    self.birdJump();
                    self.startBound();
                }
                // self.birdJump();
                // self.startBound();
                self.birdFly(count);
            }
            
        },30)
        //this---bird
        // this.skyMove();
        // this.birdJump();
      
        
       
    },

    //天空移动  
    skyMove:function(){
       //console.log(this.el)
       //this===bird
        var self=this;
        //setInterval(function(){
            //回调函数this==window
            //天空移动的速度越来越快故不能写死
            self.skyPosition -= self.skyStep;
            self.el.style.backgroundPositionX=self.skyPosition + 'px';
       // },30)

    },

    //小鸟蹦跶
    birdJump:function(){
        var self=this;
       // setInterval(function(){
             self.birdTop=self.birdTop === 220 ? 260 : 220;
             self.oBird.style.top=self.birdTop + 'px';
       // },300)
    },

    //小鸟翅膀扇动
    birdFly:function(count){
        //小鸟变化凌乱是tansition选了所有变化的改动，只需要进行top的改变即可
        this.oBird.style.backgroundPositionX=count % 3 * -30 +'px';
    },

    //点击开始后小鸟落下
    birdDrop:function(){
        this.birdTop += ++this.birdStepY;
        this.oBird.style.top=this.birdTop+"px";
        //小鸟下落碰撞
        this.judgeKnock();
        this.addScore();
    },

    //文字放大缩小
    startBound:function(){
        var prevColor=this.startColor;
        this.startColor=prevColor === 'blue'?'white':'blue';
        this.oStart.classList.remove('start-'+prevColor);
        this.oStart.classList.add('start-'+this.startColor);
        // var color;
        // if(this.startColor==='blue'){
        //     color='white';
        // }else{
        //     color='blue';
        // }
        // classList.remove('start-'+this.startColor);
        // classList.add('start-'+color);
        // this.startColor=color;

    },
    
    //小鸟下落碰撞   临界值的检测  柱子碰撞的检测
    judgeKnock:function(){
        this.judgeBoundary();
        this.judgePipe();
    },
    judgeBoundary:function(){
        if(this.birdTop < this.minTop || this.birdTop > this.maxTop) {
            this.failGame();
        }
    },
    judgePipe:function(){
        //相遇pipeX=95px    离开小鸟pipeX=13px
        var index=this.score % this.pipeLength;
        var pipeX=this.pipeArr[index].up.offsetLeft;
        var pipeY=this.pipeArr[index].y;
        var birdY=this.birdTop;
        if((pipeX<=95 && pipeX>=13)&&(birdY<=pipeY[0] || birdY>=pipeY[1])){
            this.failGame();
        }

    },
    //pipeMove 柱子移动
    pipeMove:function(){
        for(var i=0;i<this.pipeLength;i++){
            //在数组中拿取每一对柱子
            var oUpPipe=this.pipeArr[i].up;
            var oDownPipe=this.pipeArr[i].down;
            //offsetLeft直接取数值，不带px单位，可以直接进行相减
            var x=oUpPipe.offsetLeft-this.skyStep;

            //柱子循环出现
            if(x<-52){
                var lastPipeLeft=this.pipeArr[this.pipeLastIndex].up.offsetLeft;
                oUpPipe.style.left=lastPipeLeft+300+'px';
                oDownPipe.style.left=lastPipeLeft+300+'px';
                this.pipeLastIndex= ++this.pipeLastIndex % this.pipeLength;
                
                 // oUpPipe.style.height=upHeight+'px';
                // oDownPipe.style.height=downHeight+'px';

                continue;
            };
            oUpPipe.style.left=x+'px';
            oDownPipe.style.left=x+'px';

        }
    },
    //封装柱子的高度
    getPipeHeight:function(){
         var upHeight=50+Math.floor(Math.random()*175);
         var downHeight=600-150-upHeight;
         return{
             up:upHeight,
             down:downHeight,
         }
    },


    //通过柱子后加分
    addScore:function(){
        var index=this.score % this.pipeLength;
        var pipeX=this.pipeArr[index].up.offsetLeft;

        if(pipeX<13){
            // this.score++;
            this.oScore.innerText=++this.score;
        }
    },

    //监听事件
    handle:function(){
        this.handleStart();
        this.handleClick();
        this.handleRestart();
    },
    //点击开始，所发生的绑定事件
    handleStart:function(){
        // var self=this;
        this.oStart.onclick=this.start.bind(this); //用bind更改this指向
    },
    start:function(){
        var self=this;

        self.startFlag=true;
        self.oStart.style.display="none";
        self.oBird.style.transition="none";
        self.oScore.style.display="block";
        self.skyStep=5;
        self.oBird.style.left="80px";
        //createPipe 创建多对柱子，利用for循环
        //柱子到左侧的距离
        for(var i=0;i<self.pipeLength;i++){
            self.createPipe(300 * (i+1));
        };
        // self.createPipe();
    },
    //点击重新开始，所绑定的事件
    handleRestart:function(){
        this.oRestart.onclick=function(){
            sessionStorage.setItem('play',true);
            window.location.reload();
        }
    },

    createPipe:function(x){
        //0~1   空隙150  600-150=450/2=225   柱子不能低于50
        //var pipeHeight
        var upHeight=50+Math.floor(Math.random()*175);
        var downHeight=600-150-upHeight;

        var oUpPipe=createEle('div',['pipe','pipe-up'],{
            height:upHeight+'px',
            left:x+'px',
        })
       //console.log(oUpPipe);
        var oDownPipe=createEle('div',['pipe','pipe-bottom'],{
            height:downHeight+'px',
            left:x+'px',
        })
        this.el.appendChild(oUpPipe);
        this.el.appendChild(oDownPipe);

        this.pipeArr.push({
              up:oUpPipe,
              down:oDownPipe,  
              y:[upHeight,upHeight+150],     
        })
        // var oDiv=document.createElement('div');
        // oDiv.classList.add('pipe');
        // oDiv.classList.add('pipe-up');
        // oDiv.style.height=upHeight+'px';

        
        //this.el.appendChild(oDiv);
    },

    //游戏失败
    failGame:function(){
        clearInterval(this.timer);
        this.setScore();
        this.oMask.style.display="block";
        this.oEnd.style.display="block"; 
        this.oBird.style.display="none";
        this.oScore.style.display="none";
        this.oFinalScore.innerText=this.score;
        //将localStorage的数据渲染到得分列表中
        this.renderRankList();
    },
    renderRankList:function(){
        var template='';
        for(var i=0;i<8;i++){
            var degreeClass = '';
            switch(i){
                case 0:
                    degreeClass='first';
                    break;
                case 1:
                    degreeClass='second';
                    break;
                case 2:
                    degreeClass='third';
                    break;
            }
            template += `
            <li class="rank-item">
                <span class="rank-degree ${degreeClass}">${i + 1}</span>
                <span class="rank-score">${this.scoreArr[i].score}</span>
                <span class="rank-time">${this.scoreArr[i].time}</span>
            </li>
             `
             }
         this.oRankList.innerHTML=template;

    },
    
    //点击父元素   小鸟往上跳
    handleClick:function(){
        var self=this;
        this.el.onclick=function(e){
            if(!e.target.classList.contains('start')){    //除了点击开始游戏，其他父元素的任何地方小鸟跟会动
                self.birdStepY=-10;
            }
          
        }

       
    },
    


};

// bird.initData();
// bird.animate();